package com.lxk.interceptor;

import com.lxk.common.GsonUtils;
import com.lxk.dao.BlogDbDao;
import com.lxk.domain.UserDbEntity;
import com.lxk.exception.UnloginException;
import com.lxk.service.UserService;
import com.lxk.service.component.RedisClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.Optional;

/**
 * Created by Lxk on 2020/6/14.
 */
public class LoginInterceptor extends HandlerInterceptorAdapter {

    private static Logger logger = LoggerFactory.getLogger(LoginInterceptor.class);

    private RedisClient redisClient;

    private UserService userService;

    public LoginInterceptor(RedisClient redisClient, UserService userService) {
        this.redisClient = redisClient;
        this.userService = userService;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Cookie[] cookies = request.getCookies();
        if(ObjectUtils.isEmpty(cookies)){
            logger.info("访客cookie不存在 :: cookies:{}",cookies);
            throw new UnloginException("Unlogin");
        }
        Optional<Cookie> ticketCookieOptional = Arrays.stream(cookies).filter(each->"ticket".equals(each.getName())).findFirst();
        String ticket = ticketCookieOptional.isPresent() ? ticketCookieOptional.get().getValue():null;
        if(!StringUtils.isEmpty(ticket)){
            logger.info("访客光临后台 :: ticket:{}",ticket);
            String redisValue = redisClient.getKey(ticket);
            logger.info("访客光临后台 :: redisValue:{}",redisValue);
            if(StringUtils.isEmpty(redisValue)){
                //伪造的ticket或者ticket已经过期
                throw new UnloginException("Unlogin");
            }
            UserDbEntity user = GsonUtils.getGson().fromJson(redisValue,UserDbEntity.class);
            UserDbEntity dbUser = userService.checkUser(user.getUsername(),user.getPassword());
            logger.info("后台用户数据库信息查询 :: dbUser:{}",dbUser);
            if(!ObjectUtils.isEmpty(dbUser)){
                return true;
            }
        }
        throw new UnloginException("Unlogin");
    }

}
